package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQueryObject;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.springframework.data.domain.Sort.Direction.ASC;

@Service
public class RegionServiceImpl implements IRegionService {
    @Autowired
    private RegionRepository regionRepository;
    @Autowired
    private DestinationRepository destinationRepository;
    @Autowired
    private MongoTemplate template;
    @Override
    public void save(Region user) {
        user.setId(null);
        regionRepository.save(user);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void update(Region user) {
        regionRepository.save(user);
    }

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQueryObject qo) {
        //完成分页查询
        //使用MongoTemplate完成分页查询和高级查询,因为regionRepository只能完成查询全部数据的分页,无法完成高级查询
        //先查询总数据量
        //创建查询对象
        Query query = new Query();
        //查询总数据量,(高级查询)
        long count = template.count(query, Region.class);
        if(count==0){
            return Page.empty();
        }
        //查询分页数据
        //创建分页对象,参数为:当前页码,页面数据显示量,排序规则,排序字段//当前页面是从0算起的
        Pageable pageable= PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), ASC,"_id");
        //将分页对象传给查询对象
        query.with(pageable);
        //查询分页数据,第一个参数告诉查询对象,第二个参数告诉查询的集合
        List<Region> regions = template.find(query, Region.class);
        //返回分页数据封装类,springboot自带分页数据显示封装类
        return new PageImpl<>(regions,pageable,count);
    }

    @Override
    public void checkStatus(int hot,String id) {
        //根据区域id查询区域对象
        Region region1 = this.get(id);
        //修改区域对象的热门状态
        region1.setIshot(hot);
        this.update(region1);
    }

    @Override
    public List<Destination> queryByDeep(int deep) {
        return destinationRepository.findByDeep(deep);
    }
}
